import { defineStore } from 'pinia';
import { userAPI } from '@/api/user';

export const useUserStore = defineStore('user', {
    state: () => ({
        userList: [],
        pageInfo: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
            totalPage: 0
        }
    }),
    actions: {
        pageInfo: undefined,
        async getUserList(params = {}) {
            try {
                const response = await userAPI.list({
                    page: params.pageNumber || this.pageInfo.pageNum,
                    size: params.pageSize || this.pageInfo.pageSize,
                    username: params.username || '',
                    email: params.email || '',
                    mobile: params.mobile || ''
                });

                // 确保API返回的数据结构正确
                if (!response.data || !response.data.records) {
                    throw new Error('API返回的数据结构不正确');
                }


                this.userList = response.data.records;
                this.pageInfo = {
                    pageNum: response.data.pageNumber || 1,
                    pageSize: response.data.pageSize || 10,
                    total: response.data.totalRow || 0,
                    totalPage: response.data.totalPage || 0
                };

                return response.data;
            } catch (error) {
                console.error('获取用户列表失败:', error);
                throw error;
            }
        },
        //更新用户信息
        async updateUser(userData) {
            try {
                const response = await userAPI.updateUser(userData );
                return response.data;
            }catch ( error){
                console.error('更新用户信息失败:', error);
                throw error;
            }
        },
        // 删除用户
        async deleteUser(id) {
            try {
                const response = await userAPI.deleteUser(id);
                return response.data;
            } catch (error) {
                console.error('删除用户失败:', error);
                throw error;
            }
        },
    }
});